package com.aiit.controller;

import com.aiit.pojo.AUser;
import com.aiit.service.AUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class ALoginController {
    @Resource
    AUserService aUserService;
    @GetMapping("/admin/login")
    public String login() {
        return "admin/login";
    }

    @PostMapping("/tologin")
    public String tologin(AUser user, Model model, HttpServletRequest request) {
        String username = user.getUsername();
        String password = user.getPassword();

        System.out.println(user);
        AUser auser=aUserService.queryByName(username);

        try {
            //login认证通过后，便可拿到shiro保存的用户对象
            if(auser.getPassword().equals(password)){

                request.getSession().setAttribute("user", auser);
                return "redirect:/admin/index";
            }

        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名错误");
            return "admin/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            return "admin/login";
        } catch (ExcessiveAttemptsException e) {
            model.addAttribute("msg", "登录失败次数过多");
            return "admin/login";
        } catch (UnauthorizedException e) {
            model.addAttribute("msg", "您没有得到相应的授权！" + e.getMessage());
            return "admin/login";
        }
        return "redirect:admin/login";
    }

    @GetMapping("/admin/index")
    public String adminindex() {
        return "admin/index";
    }
    @GetMapping("/noauth")
    public String noauth() {
        return "admin/noauth";
    }

    @GetMapping("welcome")
    public String welcome(){
        return "welcome";
    }

}
